package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import snaq.db.ConnectionPool;

import com.mysql.jdbc.Driver;

public class ConnPool
{
	private static final String dbUrl = "jdbc:mysql://localhost:3306/ca_schemata";
	private static final String dbUserName = "root";
	private static final String dbPassword = "880527871023";
	private static Connection conn = null;
	private static ConnectionPool pool = null;
	@SuppressWarnings("rawtypes")
	private static Class c = null;
	
	public static void setupConPool() throws DAOException
	{
		try
		{
			c = Class.forName("com.mysql.jdbc.Driver");
			Driver driver = (Driver) c.newInstance();
			DriverManager.registerDriver(driver);
			pool = new ConnectionPool("local", 1, 5, 20, 180000, dbUrl,
					dbUserName, dbPassword);
		}
		catch (Exception e)
		{
			System.out.println("Failed to load JDBC driver.");
		}
	}
	
	
	public static Connection GetConnection() throws DAOException
	{
//		Test Codes use this if you not starting up the server.
//		try
//		{
//			c = Class.forName("com.mysql.jdbc.Driver");
//			Driver driver = (Driver) c.newInstance();
//			DriverManager.registerDriver(driver);
//			pool = new ConnectionPool("local", 1, 5, 20, 180000, dbUrl,
//					dbUserName, dbPassword);
//		}
//		catch (Exception e)
//		{
//			System.out.println("Failed to load JDBC driver.");
//		}
//		Test Code ends here.
		
		try
		{
			long timeout = 3000;
			conn = pool.getConnection(timeout);

		}
		catch (Exception e)
		{
			System.out.println("Error occured at connect");
		}
		
		
		if (conn != null)
		{
			return conn;
		}
		else
		{
			throw new DAOException(
					"Connection Time out, please try again later");
		}

	}
	
	public static void closeconnect(Statement stmt, ResultSet result)
	{
		try
		{
			 
			stmt.close();
			if (result != null)
			{
				result.close();
			}
			conn.close();

		}
		catch (Exception e)
		{
			System.out.println("Error occured at closing");
			System.out.println(e.toString());
		}
	}
}
